/*
 * @Description: 文章帖子
 * @Author: chenjiaxin
 * @Date: 2021-12-26 10:58:04
 * @LastEditTime: 2022-01-08 19:22:08
 * @FilePath: \novel-serve\src\controller\article.controller.js
 */
const errorTypes = require("../constants/error-types");
const service = require("../service/article.service");
const { responseHandle } = require("../utils/tool");

class ArticleController {
  /**
   * 保存文章
   * @param {*} ctx 
   * @param {*} next 
   * @returns 
   */
  async create (ctx, next) {
    try {
      //1、拿到用户id，和发表的内容
      const userId = ctx.user.id;
      const { content, title } = ctx.request.body;
      if (!content || !title) {
        // const error = new Error(errorTypes.PARAM_EMPTY);
        return ctx.app.emit('error', errorTypes.PARAM_EMPTY, ctx);
      }

      //插入数据库中
      const result = await service.create(userId, title, content);
      // ctx.body = {
      //   code: 200,
      //   data: "保存成功"
      // };
      ctx.body = responseHandle(200);
    } catch (err) {
      // const error = new Error(errorTypes.SYNTAX_ERROR);
      return ctx.app.emit('error', errorTypes.SYNTAX_ERROR, ctx, err.message);
    }
  }

  //获取文章详情
  async getArticle (ctx, next) {
    try {
      //1、拿到用户id
      // const userId = ctx.user.id;
      //文章id
      const { id } = ctx.request.query;
      // console.log(id, '==========');
      const result = await service.getArticleById(id);
      // ctx.body = {
      //   code: 200,
      //   data: result
      // };
      ctx.body = responseHandle(200, result);

    } catch (error) {
      return ctx.app.emit("error", errorTypes.SYNTAX_ERROR, ctx, error.message);
    }
  }
}

module.exports = new ArticleController();
